package com.ly.controller;


import com.ly.base.ResponseData;
import com.ly.common.FileCheck;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    @Value("${upload.path}")  // 从配置文件中获取上传文件保存路径
    private String uploadPath;


    @ApiOperation(value="上传图片")
    @PostMapping("/upload")
    @FileCheck(typeCheckErrorMsg = "不支持的文件格式", supportedSuffixes = {"txt"}, type = FileCheck.CheckType.SUFFIX)
    public ResponseData uploadFile(@RequestParam("file") MultipartFile file, Principal principal) {
        try {
            // 生成新的文件名
            String fileName = generateUniqueFileName(file.getOriginalFilename());
            // 获取项目根路径
            String rootPath = System.getProperty("user.dir");
            // 拼接文件保存路径
            String filePath = rootPath + "/uploads/" + fileName;

            // 保存文件到目标路径
            file.transferTo(new File(filePath));

//            String uploadFolder = this.getClass().getResource("/").getPath() + "/uploads/";
//
//            File dest = new File(uploadFolder + fileName);
//            // 检测文件目录是否存在 不存在则创建
//            if (!dest.getParentFile().exists()){
//                dest.getParentFile().mkdirs();
//            }
//
//            file.transferTo(dest);


            // 返回文件上传成功的响应或其他逻辑
            return ResponseData.success("文件上传成功",fileName);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理文件上传失败的逻辑
            return ResponseData.fail("文件上传失败");
        }

    }

    // 生成唯一的文件名，可以根据需要进行自定义
    private String generateUniqueFileName(String originalFileName) {
        // 这里使用UUID来生成文件名，可以根据需求进行适当调整
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String extension = extractFileExtension(originalFileName);
        String name = originalFileName.substring(0,originalFileName.lastIndexOf("."));
        return uuid +"-"+name+ "." + extension;
    }

    // 提取文件扩展名
    private String extractFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }
}
